package cz.fimuni.pa165.frontend;

import cz.fimuni.pa165.backendapi.dto.CarDTO;
import cz.fimuni.pa165.backendapi.dto.CompanyDTO;
import cz.fimuni.pa165.backendapi.dto.ReservationDTO;
import cz.fimuni.pa165.backendapi.facade.ServiceFacade;
import cz.fimuni.pa165.frontend.propertyeditor.CompanyDTOPropertyEditor;
import cz.fimuni.pa165.frontend.validator.CarValidator;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Ondřej Myška
 */
@Controller
@RequestMapping("/car")
@SessionAttributes("CarDTO")
public class CarController {

    @Autowired
    private ServiceFacade serviceFacade;
    @Autowired
    private CarValidator validator;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(CompanyDTO.class, new CompanyDTOPropertyEditor(serviceFacade));
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView carDTO(Model model) {

        CarDTO car = new CarDTO();
        car.setNumberOfSeats(4);
        car.setColour("černá");
        car.setAvailable(true);
        ModelAndView view = new ModelAndView("/car/add", "carDTO", car);

        view.addObject("companies", serviceFacade.getAllCompanies());
        return view;

    }

    @RequestMapping(value = "/save", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView addCar(@Valid @ModelAttribute("carDTO") CarDTO car, BindingResult result) {

        validator.validate(car, result);
        if (result.hasErrors()) {
            ModelAndView view = new ModelAndView("car/add", "carDTO", car);
            view.addObject("companies", serviceFacade.getAllCompanies());
            return view;
        } else {
            serviceFacade.addCar(car);
            return new ModelAndView("redirect:/car");
        }

    }

    @RequestMapping(method = RequestMethod.GET)
    public String listAllCars(Model model) {

        model.addAttribute("list", serviceFacade.getAllCars());
        return "car/list";

    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String deleteCar(@ModelAttribute("carDTO") CarDTO car, ModelMap model) {
        try {
            serviceFacade.removeCar(car);
            return "redirect:/car";
        } catch (JpaSystemException e) {

            List<ReservationDTO> dtoList = serviceFacade.getAllReservations();
            for (int i = 0; i < dtoList.size(); i++) {
                if (dtoList.get(i).getCar().getId() == car.getId()) {
                    try {
                        serviceFacade.removeReservation(dtoList.get(i));
                        serviceFacade.removeCar(car);
                    } catch (JpaSystemException ex) {
                        model.addAttribute("error", "Nelze smazat Auto... chyba databáze");
                    }
                }
            }
            model.addAttribute("error", "");
            return "redirect:/car";
        }

    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public ModelAndView editCar(@PathVariable(value = "id") String id, Model model) {
        
        long l = 0;
        try {
            l = Long.parseLong(id);
        } catch (Exception ex) {
            if (id.equals("j_spring_security_logout")){
                return new ModelAndView("redirect:/j_spring_security_logout");
            } else {
                return new ModelAndView("redirect:/car");
            }
        }

        ModelAndView view = new ModelAndView("car/edit", "carDTO", serviceFacade.find(Long.parseLong(id)));
        view.addObject("companies", serviceFacade.getAllCompanies());
        return view;

    }

    @RequestMapping(value = "/done", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView editCar(@ModelAttribute("carDTO") CarDTO car, BindingResult result) {

        validator.validate(car, result);
        if (result.hasErrors()) {
            ModelAndView view = new ModelAndView("car/edit", "carDTO", car);
            view.addObject("companies", serviceFacade.getAllCompanies());
            return view;
        } else {
            serviceFacade.updateCar(car);
            return new ModelAndView("redirect:/car");
        }

    }
}
